<?php

namespace Fox;

class DefResponse implements Response {

	const BODY_TYPE_STRING = 1;
	const BODY_TYPE_TPL = 2;
	const BODY_TYPE_FILE = 3;
	const BODY_TYPE_PHP = 4;
	const BODY_TYPE_REWRITE = 5;

	private $heads;
	private $body;
	private $bodyType;

	public function __construct($heads, $body, $bodyType = DefResponse::BODY_TYPE_STRING) {
		$this->heads = $heads;
		$this->body = $body;
		$this->bodyType = $bodyType;
	}

	/**
	 * 输出Http头和Body
	 */
	public function out() {
		$this->outHeads();
		$this->outBody();
	}

	/**
	 * 输出Http头
	 */
	private function outHeads() {
		foreach ($this->heads as $item) {
			if (is_string($item)) {
				header($item);
			} else {
				header("$item[name]: $item[value]");
			}
		}
	}

	/**
	 * 输出Http Body
	 */
	private function outBody() {
		if ($this->bodyType === self::BODY_TYPE_TPL) {
			$tpl =  boot()->config['tpl'];
			$type = $tpl['type'];
			$tpl_obj = new $type($tpl['pars']);
			$tpl_obj->include($this->body);
		} else if ($this->bodyType === self::BODY_TYPE_PHP) {
			extract(ViewData::all());
			include $this->body;
		} else if ($this->bodyType === self::BODY_TYPE_FILE) {
			ob_clean();
			@readfile($this->body);
			exit();
		} else if ($this->bodyType === self::BODY_TYPE_REWRITE) {
			boot()->rewrite($this->body);
		} else {
			echo $this->body;
		}
	}

}
